package crawler;

import java.io.File;

import org.dom4j.DocumentException;

import receipe.pushing.RecipeAllDataToPush;
import sparql.RunSparqlAddToModel;

import crawler.Crawler;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;

public class Main {
	Crawler crawler = new Crawler();

	public static void main(String[] args) throws Exception {
		String crawlStorageFolder = "/data/crawl/root";
		int numberOfCrawlers = 1;

		CrawlConfig config = new CrawlConfig();
		config.setCrawlStorageFolder(crawlStorageFolder);
		// config.setMaxPagesToFetch(7);

		/**
		 * Instantiate the controller for this crawl.
		 */
		PageFetcher pageFetcher = new PageFetcher(config);
		RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
		RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig,
				pageFetcher);
		CrawlController controller = new CrawlController(config, pageFetcher,
				robotstxtServer);

		/**
		 * For each crawl, you need to add some seed urls. These are the first
		 * URLs that are fetched and then the crawler starts following links
		 * which are found in these pages
		 */

		controller
				.addSeed("http://www.food.com/slideshow/15-quick-easy-chicken-dinners-130/cajun-chicken-pasta-8");

		/**
		 * Start the crawl. This is a blocking operation, meaning that your code
		 * will reach the line after this only when crawling is finished.
		 */
		controller.start(Crawler.class, numberOfCrawlers);

		//We call here method which knows to add saved rdf 
		//files to model and make 
		//sparql queries
		
		System.out.println("CRWAWL FINISHED, WAIT FOR SPARQL.");
		RunSparqlAddToModel.addAndRun();
	}
	
	//Not using this method now because of testing saved rdfs. It will be called when we want to delete files
	//after making SPARQL queries, to free up resources for new files

//	public static void deleteFile() {
//		try {
//			int i = 0;
//			while (true) {
//				File file = new File("recipesData" + i + ".xml");
//				if (file.delete()) {
//					i++;
//				} else {
//					break;
//				}
//			}
//
//		} catch (Exception e) {
//
//			e.printStackTrace();
//
//		}
//
//	}
}
